package com.tjdx.projectsubmission.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tjdx.projectsubmission.db.entity.Quarter;
import com.tjdx.projectsubmission.db.entity.User;
import com.tjdx.projectsubmission.db.mapper.QuarterMapper;
import com.tjdx.projectsubmission.db.mapper.UserMapper;
import com.tjdx.projectsubmission.service.UserService;
import com.tjdx.projectsubmission.util.DateUtil;
import com.tjdx.projectsubmission.vo.QueryParam;
import com.tjdx.projectsubmission.vo.R;
import com.tjdx.projectsubmission.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private QuarterMapper quarterMapper;

    @Override
    public R insertUser(User user) {
        if (user == null) return R.error().message("参数错误");

        // 用户名
        String username = user.getUsername();

        // 构建条件对象, 查询是否已经存在用户名
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("id");
        wrapper.eq("username", username);
        wrapper.last("limit 1");

        // 查询判断, 如果查询出来有数据, 则不为null
        if (this.baseMapper.selectOne(wrapper) != null) R.error().message("该用户名已存在");

        // 执行插入数据操作
        return this.baseMapper.insert(user) == 0 ? R.error().message("添加用户失败") : R.ok();
    }

    @Override
    public R deleteUser(Integer id) {
        if (id == null || id <= 0) return R.error().message("参数错误");

        return this.baseMapper.deleteById(id) == 0 ? R.error().message("删除失败") : R.ok();
    }

    @Override
    public R deleteUserMore(List<Integer> ids) {
        if (ids.size() == 0) return R.error().message("参数错误");

        return this.baseMapper.deleteBatchIds(ids) != ids.size() ? R.error().message("删除失败") : R.ok();
    }

    @Override
    public R modifyUser(User user) {
        if (user == null || user.getId() == null || user.getId() <= 0) return R.error().message("参数错误");

        return this.baseMapper.updateById(user) == 0 ? R.error().message("编辑用户失败") : R.ok();
    }

    @Override
    public R findUserList(Integer index, Integer size, QueryParam queryParam) {
        if (index == null || size == null || index <= 0 || size <= 0) {
            return R.error().message("参数错误");
        } else if (size > 10) {
            return R.error().message("一次最多10条数据");
        }

        // 构建分页对象
        Page<User> page = new Page<>(index, size);
        // 查询
        IPage<User> iPage = this.baseMapper.findUserList(page, queryParam);

        // 回传两个数据, 一个 userList --> 用户数据列表, 一个 total -> 总页数
        return R.ok().data("userList", iPage.getRecords()).data("total", iPage.getTotal());
    }

    @Override
    public R getUserInfoById(Integer id) {
        if (id == null || id <= 0) return R.error().message("参数错误");

        return R.ok().data("userInfo", this.baseMapper.selectById(id));
    }

    @Override
    public R login(User user, HttpServletRequest request) {
        String username = user.getUsername();
        String password = user.getPassword();
        String role = user.getRole();
        if (username == null || password == null || role == null) {
            return R.error().message("参数错误");
        }
        // 构建条件对象, 查询是否已经存在用户名
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        /*        wrapper.eq("role",role);*/
        wrapper.eq("username", username);
        wrapper.last("limit 1");
        // 查询判断, 如果查询出来有数据, 则不为null
        User userInfo = this.baseMapper.selectOne(wrapper);
        if (userInfo == null) {
            return R.error().message("用户不存在");
        }
        if (!role.equals(userInfo.getRole())) {
            return R.error().message("角色选择错误");
        }
        if (!password.equals(userInfo.getPassword())) {
            return R.error().message("密码错误");
        }
        userInfo.setPassword(null);
 /*       userInfo.setToken(UUID.randomUUID().toString());*/

        HttpSession session= request.getSession();
        session.setAttribute("userInfo",userInfo);
        session.setAttribute("userId",userInfo.getId());
        session.setAttribute("roleId",userInfo.getRole());
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userInfo,userVo);


        Date serveTime = new Date();
        String quarter = DateUtil.quarter(DateUtil.getMM(serveTime));
        int weeks = DateUtil.getWeek(serveTime);
        String year = DateUtil.getSysYear();
        String dateStr = year+"年第"+quarter+"季度第"+weeks+"周";

        QueryWrapper<Quarter> queryByDateStr = new QueryWrapper<>();
        queryByDateStr.eq("name",dateStr);
        List<Quarter> quarterList = quarterMapper.selectList(queryByDateStr);
        if (quarterList == null || quarterList.isEmpty()){
            Date date = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHH");
            Quarter q = new Quarter();
            q.setName(dateStr);
            q.setSort(Integer.parseInt(df.format(date)));
            quarterMapper.insert(q);
        }

        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("sort");
        userVo.setQuarterList(quarterMapper.selectList(queryWrapper));
        return R.ok().data("userInfo", userVo);
    }
}
